<?php

namespace app\service\shopify\action\graph;

use app\model\Shops;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use PHPShopify\ShopifySDK;
use think\helper\Arr;


class GraphQLBase
{
    protected Shops $shop;
    protected bool $isAdmin = false;

    public function __construct(int $shop_id, bool $isAdmin = false)
    {
        $this->isAdmin = $isAdmin;
        $this->shop = Shops::find($shop_id);
    }

    public function post(string $query, array $variables = [])
    {
        $adminEndpoint = sprintf("https://%s.myshopify.com/admin/api/%s/graphql.json", $this->shop->name, $this->shop->version);
        $storeEndpoint = sprintf("https://%s.myshopify.com/api/%s/graphql.json", $this->shop->name, $this->shop->version);
        $graphqlEndpoint = $this->isAdmin ? $adminEndpoint : $storeEndpoint;
        $headerToken = $this->isAdmin ? ['X-Shopify-Access-Token' => $this->shop->admin_token] : ['X-Shopify-Storefront-Access-Token' => $this->shop->store_token];
        $header = ['Content-Type' => 'application/json',];
        $header = array_merge($header, $headerToken);
        $client = new Client(
            [
                'timeout' => 120,
                'verify' => false,
            ] // 生产环境应为true，开发环境可设为false跳过SSL验证]
        );
        $json = ['query' => $query];
        if ($variables) $json['variables'] = $variables;
        $log = [
            'url' => $graphqlEndpoint,
            'params' => $json,
            'response' => [],
            'error' => [],
            'headers' => $header
        ];
        try {
            $response = $client->post($graphqlEndpoint, ['headers' => $header, 'json' => $json]);
            $content = $response->getBody()->getContents();
            $response = json_decode($content, true);
            $log['response'] = $response;
            tplog($this->isAdmin ? "adminAPI" : "StorefrontAPI", $log, 'shopify');
            if($errors = Arr::get($response, 'errors',[])){
                throw new \Exception(implode(',',array_column($errors,'message')));
            }
            return $response;
        } catch (RequestException $e) {
            $log['error'] = $e->getMessage();
            // 错误处理
            if ($e->hasResponse()) {
                $errorResponse = json_decode($e->getResponse()->getBody(), true);
                if (isset($errorResponse['errors'])) {
                    $log['error'] = $errorResponse['errors'];
                }
            }
            tplog($this->isAdmin ? "adminAPI" : "StorefrontAPI", $log, 'shopify');
            throw new \Exception($e->getMessage(), $e->getCode());
        } catch (\Exception $e) {
            $log['error'] = $e->getMessage();
            tplog($this->isAdmin ? "adminAPI" : "StorefrontAPI", $log, 'shopify');
            throw $e;
        }
    }

}